﻿#include "transfer_storage.h"
#include "ui_transfer_storage.h"

//tablewidget的列号
#define DetailID 0
#define ChooseProduct 1
#define ProductCode 2
#define ProductName 3
#define ProductType 4
#define ChooseBatch 5
#define ProductBatch 6
#define OutLocation 7
#define OutStorageNum 8
#define IntoLocation 9
#define IntoStorageNum 10
#define TransferNum 11
#define DIGIT "^[0-9]*$"   //仅输入数字的正则

TransferStorage::TransferStorage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TransferStorage)
{
    ui->setupUi(this);

    ui->out_storage_combo->addItems(WarehouseList());
    ui->out_storage_combo->setCurrentIndex(-1);
    ui->into_storage_combo->addItems(WarehouseList());
    ui->into_storage_combo->setCurrentIndex(-1);

    ui->tableWidget->verticalHeader()->setVisible(false);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->setFocusPolicy(Qt::NoFocus);
    ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(ChooseProduct,QHeaderView::Fixed);//第二列“产品选择”宽度设置
    ui->tableWidget->setColumnWidth(ChooseProduct,75);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(ChooseBatch,QHeaderView::Fixed);//第六列“批次选择”宽度设置
    ui->tableWidget->setColumnWidth(ChooseBatch,75);

    //设置列不可编辑
    ReadOnlyDelegate* readOnlyDelegate = new ReadOnlyDelegate(this);
    ui->tableWidget->setItemDelegateForColumn(DetailID, readOnlyDelegate);
    ui->tableWidget->setItemDelegateForColumn(ProductCode, readOnlyDelegate);
    ui->tableWidget->setItemDelegateForColumn(ProductName, readOnlyDelegate);
    ui->tableWidget->setItemDelegateForColumn(ProductType, readOnlyDelegate);
    ui->tableWidget->setItemDelegateForColumn(ProductBatch, readOnlyDelegate);
    ui->tableWidget->setItemDelegateForColumn(OutStorageNum, readOnlyDelegate);
    ui->tableWidget->setItemDelegateForColumn(IntoStorageNum, readOnlyDelegate);

    //设置列输入格式
    SetTextDelegate* setTextDelegate = new SetTextDelegate(this);
    setTextDelegate->reg = new QRegExpValidator(QRegExp(DIGIT));
    setTextDelegate->MaxLength = 5;
    ui->tableWidget->setItemDelegateForColumn(TransferNum, setTextDelegate);



    RightClickMenu=new QMenu(ui->tableWidget);
    m_addAction=new QAction(QString::fromUtf8("插入"),this);
    m_deleteAction=new QAction(QString::fromUtf8("删除"),this);
    RightClickMenu->addAction(m_addAction);
    RightClickMenu->addAction(m_deleteAction);

    connect(ui->tableWidget,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(RightClickSlot(QPoint)));
    connect(RightClickMenu,SIGNAL(triggered(QAction*)),this,SLOT(RightClickAddRow(QAction*)));
    connect(RightClickMenu,SIGNAL(triggered(QAction*)),this,SLOT(RightClickDeleteRow(QAction*)));
}

TransferStorage::~TransferStorage()
{
    delete ui;
}

QString TransferStorage::tableCellText(int row, int column)
{
    switch (column) {
    case DetailID :
        return ui->tableWidget->item(row,column)->text();
        break;
    case ProductCode:
        return ui->tableWidget->item(row,column)->text();
        break;
    case ProductName:
        return ui->tableWidget->item(row,column)->text();
        break;
    case ProductType:
        return ui->tableWidget->item(row,column)->text();
        break;
    case ProductBatch:
        return ui->tableWidget->item(row,column)->text();
        break;
    case OutLocation:
    {
        DatabaseComboBox *cbbox = (DatabaseComboBox*)( ui->tableWidget->cellWidget(row, column));
        return cbbox->currentText();
        break;
    }
    case OutStorageNum:
        return ui->tableWidget->item(row,column)->text();
        break;
    case IntoLocation:
    {
        DatabaseComboBox *cbbox = (DatabaseComboBox*)( ui->tableWidget->cellWidget(row, column));
        return cbbox->currentText();
        break;
    }
    case IntoStorageNum:
        return ui->tableWidget->item(row,column)->text();
        break;
    case TransferNum:
        return ui->tableWidget->item(row,column)->text();
        break;
    default:
        break;
    }
    return nullptr;
}

void TransferStorage::RowInit(int index)
{
    ui->tableWidget->disconnect(SIGNAL(cellChanged(int,int))); //断开槽函数连接
    ui->tableWidget->insertRow(index); //在最后一行的后面插入一行

    //在插入的行中输入按钮——从数据库获得数据, 放在表格第2列
    QPushButton *choose_product_btn = new QPushButton();
    choose_product_btn->setProperty("type", "databaseBtn");
    choose_product_btn->setUpdatesEnabled(true);
    QWidget *widget = new QWidget();
    QHBoxLayout *layout = new QHBoxLayout();
    layout->addWidget(choose_product_btn);
    layout->setAlignment(choose_product_btn, Qt::AlignCenter);//控件在布局中居中显示
    widget->setLayout(layout);
    ui->tableWidget->setCellWidget(index, ChooseProduct, widget);
    connect(choose_product_btn, &QPushButton::clicked, this, &TransferStorage::choose_product_btn_clicked);

    //在插入的行中输入按钮——从数据库获得数据, 放在表格6列
    QPushButton *choose_batch_btn = new QPushButton();
    choose_batch_btn->setProperty("type", "databaseBtn");
    choose_batch_btn->setUpdatesEnabled(true);
    QWidget *widget1 = new QWidget();
    QHBoxLayout *layout1 = new QHBoxLayout();
    layout1->addWidget(choose_batch_btn);
    layout1->setAlignment(choose_batch_btn, Qt::AlignCenter);//控件在布局中居中显示
    widget1->setLayout(layout1);
    ui->tableWidget->setCellWidget(index, ChooseBatch, widget1);
    connect(choose_batch_btn, &QPushButton::clicked, this, &TransferStorage::choose_batch_btn_clicked);

    DatabaseComboBox *Out_combo=new DatabaseComboBox();
    Out_combo->setProperty("type", "dataBaseCombo"); //数据库选择框样式
    Out_combo->setProperty("row", index);
    ui->tableWidget->setCellWidget(index, OutLocation, Out_combo);
    connect(Out_combo, SIGNAL(currentTextChanged(QString)),this,SLOT(Out_combo_currentTextChanged(QString)));

    DatabaseComboBox *Into_combo=new DatabaseComboBox();
    Into_combo->setProperty("type", "dataBaseCombo"); //数据库选择框样式
    Into_combo->setProperty("row", index);
    ui->tableWidget->setCellWidget(index, IntoLocation, Into_combo);
    connect(Into_combo, SIGNAL(currentTextChanged(QString)),this,SLOT(Into_combo_currentTextChanged(QString)));

    for(int i=0;i<ui->tableWidget->columnCount();i++)
    {
        if(i==ChooseProduct || i==ChooseBatch || i==OutLocation || i==IntoLocation)
            continue;
        else
        {
            QTableWidgetItem *item = new QTableWidgetItem();
            ui->tableWidget->setItem(index,i,item);
            ui->tableWidget->item(index,i)->setTextAlignment(Qt::AlignCenter | Qt::AlignCenter);
        }
    }
    //恢复连接
    connect(ui->tableWidget,SIGNAL(cellChanged(int,int)),this,SLOT(on_tableWidget_cellChanged(int,int)));

    //生成序号
    DetailIDGenerate(index);
}

void TransferStorage::RowDelete(int index)
{
    if(index!=-1)
    {
        for(int i=0;i<ui->tableWidget->columnCount();i++)
        {
            QWidget *widget=ui->tableWidget->cellWidget(index,i);
            //确保不为空
            if(widget)
            {
                ui->tableWidget->removeCellWidget(index,i);
                delete widget;  //释放
            }
        }
        ui->tableWidget->removeRow(index);
    }
}

QStringList TransferStorage::getLocationlist(int row, bool isOutStorage)
{
    QStringList list;
    list.clear();

    if(ui->tableWidget->item(row,ProductCode) ==nullptr
            || ui->tableWidget->item(row,ProductBatch) ==nullptr
            || tableCellText(row,ProductCode) ==nullptr
            || tableCellText(row,ProductBatch) ==nullptr
            || Out_type==nullptr || Into_type == nullptr)

        return list;

    if(isOutStorage)
    {
        QSqlQuery query = mydb->ExactMatchQuery(QString("storage_space_%1_table").arg(Out_type),"ProductCode"
                                                ,tableCellText(row,ProductCode));  //mysql不区分大小写
        //展示已填充的货位
        while(query.next())
        {
            if(query.value(1).toString()==tableCellText(row,ProductBatch) && query.value(3).toInt() != 0)
            {
                 list.append(query.value(0).toString());
            }
        }
        return list;
    }

    else
    {
        QSqlQuery query = mydb->ExactMatchQuery(QString("storage_space_%1_table").arg(Into_type),"ProductCode"
                                                ,tableCellText(row,ProductCode));  //mysql不区分大小写
        //优先展示已填充的货位
        while(query.next())
        {
            if(query.value(1).toString()==tableCellText(row,ProductBatch))
            {
                int num = query.value(4).toInt()-query.value(3).toInt();
                if(num>0)
                    list.append(query.value(0).toString()+QString(" (余%1)").arg(num));
            }
        }
        //展示未填充的货位
        if((!query.exec(QString("SELECT * FROM storage_space_%1_table WHERE ProductNum=0; ").arg(Into_type)))) //如果list为空，且填满
        {
            if(list.empty())
                warning(this, "该仓库没有相匹配的货位");
            return list;
        }
        while(query.next())
        {
            int num = query.value(4).toInt()-query.value(3).toInt();
            list.append(query.value(0).toString()+QString(" (余%1)").arg(num));
        }

        list.removeDuplicates();  //移除重复元素
        return list;
    }
}

//移库单生成
//eg: Y1Y2 20231023 01, 14位
void TransferStorage::IDGenerate()
{
    if(ui->type_combo->currentIndex()==-1)   //移库类型未选
        return;

    if(ui->out_storage_combo->currentIndex()==-1 || ui->into_storage_combo->currentIndex()== -1)   //移库仓库未选
        return;

    if(ui->start_date->currentText()=="")     //入库时间未选
        return;

    QString time=ui->start_date->dateToStr().remove(QChar('-'), Qt::CaseInsensitive),   //去除字符‘-’
            limit = Out_type+Into_type;

    limit += time;
    QSqlQuery query= mydb->SortData("transfer_storage_record_table","TransferStorageRecordID",false,"TransferStorageRecordID",limit); //降序排列
    if(query.next())
    {
        QString str=query.value(0).toString();
        QString num=NumberIncrease(str.right(2)); //截取后2位,自增
        ui->ID->setText(limit+num);
    }
    else
        ui->ID->setText(limit+"01");
}

// 详细单号生成
//eg: Y1Y2 20231023 01 01, 16位
void TransferStorage::DetailIDGenerate(int index)
{
    if(ui->tableWidget->rowCount()==0 || ui->ID->text()==nullptr)
        return;

    QString limit=ui->ID->text();
    for(int i=index; i<ui->tableWidget->rowCount(); i++)
    {
        if(i==0)
            ui->tableWidget->item(i,DetailID)->setText(limit+"01");
        else
        {
            QString num=NumberIncrease(ui->tableWidget->item(i-1,DetailID)->text().right(2)); //截取上一单元格后2位,自增
            ui->tableWidget->item(i,DetailID)->setText(limit+num);
        }
    }
}

bool TransferStorage::CheckTable()
{
    for(int i=0; i<ui->tableWidget->rowCount();i++)
    {
        for(int j=2;j<ui->tableWidget->columnCount();j++)   //前两列不用检查
        {
            if(j == ChooseBatch) //选择批次列是按钮，不检查
                continue;

            if(tableCellText(i,j)==nullptr)
                return false;
        }
    }
    return true;
}

//调拨出库
bool TransferStorage::OutStorage()
{
    QString ID = StorageID("C");
    QStringList IDlist = StorageDetailID("C", ui->tableWidget->rowCount());
    if(IDlist.empty())
        return true;

    QSqlQuery query;

    //更新 货位表
    query.prepare(QString("UPDATE storage_space_%1_table SET ProductNum=:ProductNum"
                          " WHERE LocationID = :LocationID").arg(Out_type));
    for(int i=0;i<ui->tableWidget->rowCount();i++)
    {
        query.bindValue(":LocationID",tableCellText(i, OutLocation));
        int num = tableCellText(i, OutStorageNum).toInt() - tableCellText(i,TransferNum).toInt();
        query.bindValue(":ProductNum", num);
        if(!query.exec())
        {
            qDebug()<<"OutStorage 1"<<query.lastError();
            return false;
        }
    }
    query.clear();  //清空sql语句

    //插入 出库单表
    QString sql = QString("INSERT INTO out_storage_record_table(StorageRecordID,StorageType,StorageWarehouse,ResponsiblePersonID,dt)"
                          " VALUES ('%1','%2','%3','%4','%5');")
            .arg(ID)
            .arg("调拨出库")
            .arg(ui->out_storage_combo->currentText())
            .arg(ui->select_member_btn->text().left(ui->select_member_btn->text().indexOf("(")))
            .arg(ui->start_date->currentText());
    if(!query.exec(sql))
    {
        qDebug()<<"OutStorage 2"<<query.lastError();
        return false;
    }
    query.clear();  //清空sql语句

    //插入 出库详细信息表
    query.prepare(QString("INSERT INTO out_storage_detail_table(StorageDetailID,ProductCode,ProductType,ProductBatch,OUTQTY,LocationID)"
                          " VALUES (:StorageDetailID,:ProductCode,:ProductType,:ProductBatch,:OUTQTY,:LocationID);"));
    for(int i=0;i<ui->tableWidget->rowCount();i++)
    {
        query.bindValue(":StorageDetailID",IDlist.at(i));
        query.bindValue(":ProductCode", tableCellText(i,ProductCode));
        query.bindValue(":ProductType", tableCellText(i,ProductType));
        query.bindValue(":ProductBatch", tableCellText(i,ProductBatch));
        query.bindValue(":OUTQTY", tableCellText(i,TransferNum).toInt());
        query.bindValue(":LocationID",tableCellText(i,OutLocation));
        if(!query.exec())
        {
            qDebug()<<"OutStorage 3"<<query.lastError();
            return false;
        }
    }
    query.clear();  //清空sql语句

    //插入 出库关系表
    query.prepare(QString("INSERT INTO out_storage_relation_table(StorageRecordID,StorageDetailID)"
                          " VALUES (:StorageRecordID,:StorageDetailID);"));
    query.bindValue(":StorageRecordID",ID);
    for(int i=0;i<ui->tableWidget->rowCount();i++)
    {
        query.bindValue(":StorageDetailID", IDlist.at(i));
        if(!query.exec())
        {
            qDebug()<<"OutStorage 4"<<query.lastError();
            return false;
        }
    }
    query.clear();  //清空sql语句

    return true;
}

//调拨入库
bool TransferStorage::InStorage()
{
    QString ID = StorageID("R");
    QStringList IDlist = StorageDetailID("R", ui->tableWidget->rowCount());
    if(IDlist.empty())
        return true;

    QSqlQuery query;

    //更新 货位表  ,如果表中有，则修改
    query.prepare(QString("UPDATE storage_space_%1_table "
                          "SET ProductBatch=:ProductBatch, ProductCode=:ProductCode, ProductNum=:ProductNum "
                          "WHERE LocationID = :LocationID").arg(Into_type));
    for(int i=0;i<ui->tableWidget->rowCount();i++)
    {
        query.bindValue(":LocationID",tableCellText(i,IntoLocation).left(5));  //截取前两位，Y1001 （余58） 取前5位
        query.bindValue(":ProductBatch",tableCellText(i,ProductBatch));
        query.bindValue(":ProductCode", tableCellText(i,ProductCode));
        int num = tableCellText(i,IntoStorageNum).toInt() + tableCellText(i,TransferNum).toInt();
        query.bindValue(":ProductNum", num);
        if(!query.exec())
        {
            qDebug()<<"InStorage 1"<<query.lastError();
            return false;
        }
    }
    query.clear();  //清空sql语句

    //插入 入库单表
    QString sql = QString("INSERT INTO storage_record_table(StorageRecordID,StorageType,StorageWarehouse,ResponsiblePersonID,dt)"
                          " VALUES ('%1','%2','%3','%4','%5');")
            .arg(ID)
            .arg("调拨入库")
            .arg(ui->into_storage_combo->currentText())
            .arg(ui->select_member_btn->text().left(ui->select_member_btn->text().indexOf("(")))
            .arg(ui->start_date->currentText());
    if(!query.exec(sql))
    {
        qDebug()<<"InStorage 2"<<query.lastError();
        return false;
    }
    query.clear();  //清空sql语句

    //插入 入库详细信息表
    query.prepare(QString("INSERT INTO storage_detail_table(StorageDetailID,ProductCode,ProductType,ProductBatch,INQTY,LocationID)"
                          " VALUES (:StorageDetailID,:ProductCode,:ProductType,:ProductBatch,:INQTY,:LocationID);"));
    for(int i=0;i<ui->tableWidget->rowCount();i++)
    {
        query.bindValue(":StorageDetailID",IDlist.at(i));
        query.bindValue(":ProductCode", tableCellText(i,ProductCode));
        query.bindValue(":ProductType", tableCellText(i,ProductType));
        query.bindValue(":ProductBatch", tableCellText(i,ProductBatch));
        query.bindValue(":INQTY", tableCellText(i,TransferNum).toInt());
        query.bindValue(":LocationID",tableCellText(i,IntoLocation).left(5));  //截取前两位，Y1001 （余58） 取前5位
        if(!query.exec())
        {
            qDebug()<<"InStorage 3"<<query.lastError();
            return false;
        }
    }
    query.clear();  //清空sql语句

    //插入 入库关系表
    query.prepare(QString("INSERT INTO storage_relation_table(StorageRecordID,StorageDetailID)"
                          " VALUES (:StorageRecordID,:StorageDetailID);"));
    query.bindValue(":StorageRecordID",ID);

    for(int i=0;i<ui->tableWidget->rowCount();i++)
    {
        query.bindValue(":StorageDetailID", IDlist.at(i));
        if(!query.exec())
        {
            qDebug()<<"InStorage 4"<<query.lastError();
            return false;
        }
    }

    return true;
}

// 入库单号生成
//eg: R Y1 20231023 001 , 14位
QString TransferStorage::StorageID(QString str)
{
    QString time=ui->start_date->dateToStr().remove(QChar('-'), Qt::CaseInsensitive);   //去除字符‘-’
    QString limit;
    QSqlQuery query;

    if(str == "R")
    {
        limit = str + Into_type + time;
        query= mydb->SortData("storage_record_table","StorageRecordID",false,"StorageRecordID",limit); //降序排列
    }
    else if(str == "C")
    {
        limit = str + Out_type + time;
        query= mydb->SortData("out_storage_record_table","StorageRecordID",false,"StorageRecordID",limit); //降序排列
    }

    if(query.next())
    {
        QString str=query.value(0).toString();
        QString num=NumberIncrease(str.right(3)); //截取后3位,自增
        return (limit+num);
    }
    else
        return (limit+"001");
}

// 入库详细单号生成
//eg: R Y1 20231023 001 01 , 16位
QStringList TransferStorage::StorageDetailID(QString str, int rowCount)
{
    QString limit=StorageID(str);
    QStringList list;
    for(int i=0 ; i<rowCount; i++)
    {
        list.append(limit + QString("%1").arg(i+1,2,10,QLatin1Char('0')));
    }

    return list;
}

int TransferStorage::getLocationMAXMUM(QString keytype, int row, QString Location)
{
    if(row < 0)
        return 0;

    QSqlQuery query = mydb->ExactMatchQuery(QString("storage_space_%1_table").arg(keytype),"LocationID"
                                            ,Location);
    if(!query.next())
    {
        qDebug()<<"getLocationMAXMUM: "<<query.lastError();
        return 0;
    }
    return query.value(4).toInt();
}

void TransferStorage::RightClickSlot(QPoint pos)
{

    QModelIndex index = ui->tableWidget->indexAt(pos);    //找到tableview当前位置信息
    iPosRow = index.row();    //获取到了当前右键所选的行数
    if(index.isValid())        //如果行数有效，则显示菜单
    {
        RightClickMenu->exec(QCursor::pos());
    }

}

void TransferStorage::RightClickAddRow(QAction *act)
{
    if(act->text() == QString::fromUtf8("插入"))   //选中了插入这个菜单
    {
        RowInit(iPosRow);
    }
}

void TransferStorage::RightClickDeleteRow(QAction *act)
{
    if(act->text() == QString::fromUtf8("删除"))   //选中了删除这个菜单
    {
        RowDelete(iPosRow);
    }
}

void TransferStorage::choose_product_btn_clicked()
{
    QPushButton* btn = qobject_cast<QPushButton*>(this->sender());
    if (btn == nullptr)
        return;

    // 获取按钮所在的行和列
    QModelIndex qIndex = ui->tableWidget->indexAt(QPoint(btn->parentWidget()->frameGeometry().x(), btn->parentWidget()->frameGeometry().y()));
    row = qIndex.row();

    //按钮状态选择
    if(btn->property("type")=="check")
    {
        btn->setProperty("type","checked");
        style()->polish(btn);
        vecItemIndex.push_back(row);//存储选中的行号
    }
    else if(btn->property("type")=="checked")
    {
        btn->setProperty("type","check");
        style()->polish(btn);
        vecItemIndex.erase(std::remove(vecItemIndex.begin(), vecItemIndex.end(), row), vecItemIndex.end()); //删除选中的行号
    }
    else if(btn->property("type")=="databaseBtn")
    {
        //创建数据选择子界面
        dc=new DataChoose();
        dc->setTitle("选择产品");
        dc->myModel->setQuery(QString("SELECT ProductCode, ProductName, ProductType FROM product_data_table"));
        dc->myModel->setHeaderData(0,Qt::Horizontal,"产品编码");
        dc->myModel->setHeaderData(1,Qt::Horizontal,"产品名称");
        dc->myModel->setHeaderData(2,Qt::Horizontal,"产品类型");
        dc->show();
        //子界面向主界面传送选择的数据
        connect(dc,static_cast<void(DataChoose::*)(const QModelIndexList&)>(&DataChoose::singal_selectedItems),
                this, [this](const QModelIndexList& list)
        {
            ui->tableWidget->item(row,ProductCode)->setText(list[0].data().toString());
            ui->tableWidget->item(row,ProductName)->setText(list[1].data().toString());
            ui->tableWidget->item(row,ProductType)->setText(list[2].data().toString());
        });
    }
}

void TransferStorage::choose_batch_btn_clicked()
{
    QPushButton* btn = qobject_cast<QPushButton*>(this->sender());
    if (btn == nullptr)
        return;

    // 获取按钮所在的行
    QModelIndex qIndex = ui->tableWidget->indexAt(QPoint(btn->parentWidget()->frameGeometry().x(), btn->parentWidget()->frameGeometry().y()));
    row = qIndex.row();

    if(Out_type == nullptr || Into_type == nullptr
            || tableCellText(row, ProductCode) == nullptr)
        return;

    //创建数据选择子界面
    dc=new DataChoose();
    dc->setTitle(QString("选择<font color=#00B050>%1").arg(tableCellText(row,ProductName)) + "<font color=black>批次");
    dc->myModel->setQuery(QString("SELECT ProductBatch, ProductNum, LocationID FROM storage_space_%1_table"
                                  " WHERE ProductCode = '%2' AND ProductNum != 0")
                            .arg(Out_type).arg(tableCellText(row, ProductCode)));
    if(dc->myModel->rowCount()==0)
    {
        delete dc;
        warning(this , "该产品目前仓库无货");
        return;
    }
    dc->myModel->setHeaderData(0,Qt::Horizontal,"产品批次");
    dc->myModel->setHeaderData(1,Qt::Horizontal,"当前数量");
    dc->myModel->setHeaderData(2,Qt::Horizontal,"货位号");
    dc->show();

    //子界面向主界面传送选择的数据
    connect(dc,static_cast<void(DataChoose::*)(const QModelIndexList&)>(&DataChoose::singal_selectedItems),
            this, [this](const QModelIndexList& list)
    {
        ui->tableWidget->item(row,ProductBatch)->setText(list[0].data().toString());
    });
}

void TransferStorage::Out_combo_currentTextChanged(QString arg)
{
    if(arg=="")
        return;
    QSqlQuery query = mydb->ExactMatchQuery(QString("storage_space_%1_table").arg(Out_type),"LocationID"
                                            ,arg);  //mysql不区分大小写
    QComboBox* combo = qobject_cast<QComboBox*>(this->sender());
    int thisrow= combo->property("row").toInt();
    if(query.next())
        ui->tableWidget->item(thisrow, OutStorageNum)->setText(query.value(3).toString());

}

void TransferStorage::Into_combo_currentTextChanged(QString arg)
{
    if(arg=="")
        return;
    QSqlQuery query = mydb->ExactMatchQuery(QString("storage_space_%1_table").arg(Into_type),"LocationID"
                                            ,arg.left(arg.indexOf(" ")));  //mysql不区分大小写
    QComboBox* combo = qobject_cast<QComboBox*>(this->sender());
    int thisrow= combo->property("row").toInt();
    if(query.next())
        ui->tableWidget->item(thisrow, IntoStorageNum)->setText(query.value(3).toString());
}

//表格中添加新行
void TransferStorage::on_add_btn_clicked()
{
    if(ui->add_btn->text()=="添加")
    {
        RowInit(ui->tableWidget->rowCount());
    }
    else if(ui->add_btn->text()=="取消操作")
    {
        for(int i=0;i<ui->tableWidget->rowCount();i++)
        {
            QWidget *widget=ui->tableWidget->cellWidget(i,1);
            if(widget)
            {
                QPushButton* btn = dynamic_cast<QPushButton*>(widget->layout()->itemAt(0)->widget());
                btn->setProperty("type","databaseBtn");
                style()->polish(btn);
            }
        }

        ui->delete_btn->setText(QString::fromUtf8("删除"));
        ui->delete_btn->setProperty("type","deleteData");
        style()->polish(ui->delete_btn);

        ui->add_btn->setText(QString::fromUtf8("添加"));
        ui->add_btn->setProperty("type","addData");
        style()->polish(ui->add_btn);
    }
}

//表格中删除选中行
void TransferStorage::on_delete_btn_clicked()
{
    if(ui->delete_btn->text()=="删除")
    {
        for(int i=0;i<ui->tableWidget->rowCount();i++)
        {
            QWidget *widget=ui->tableWidget->cellWidget(i,1);
            if(widget)
            {
                QPushButton* btn = dynamic_cast<QPushButton*>(widget->layout()->itemAt(0)->widget());
                btn->setProperty("type","check");
                style()->polish(btn);
            }
        }
        ui->delete_btn->setText(QString::fromUtf8("删除选中"));
        ui->delete_btn->setProperty("type","deleteConfirm");
        style()->polish(ui->delete_btn);

        ui->add_btn->setText(QString::fromUtf8("取消操作"));
        ui->add_btn->setProperty("type","deleteCancel");
        style()->polish(ui->add_btn);
    }
    else if(ui->delete_btn->text()=="删除选中")
    {
        sort(vecItemIndex.rbegin(), vecItemIndex.rend());
        for (unsigned int i = 0 ; i < vecItemIndex.size(); i++)
        {
            RowDelete(vecItemIndex[i]);
        }
        vecItemIndex.clear();  //清空容器
        vecItemIndex.shrink_to_fit();   //将容器的容量缩减至和实际存储元素的个数相等，释放内存

        ui->delete_btn->setText(QString::fromUtf8("删除"));
        ui->delete_btn->setProperty("type","deleteData");
        style()->polish(ui->delete_btn);

        ui->add_btn->setText(QString::fromUtf8("添加"));
        ui->add_btn->setProperty("type","addData");
        style()->polish(ui->add_btn);

        for(int i=0;i<ui->tableWidget->rowCount();i++)
        {
            QWidget *widget=ui->tableWidget->cellWidget(i,1);
            if(widget)
            {
                QPushButton* btn = dynamic_cast<QPushButton*>(widget->layout()->itemAt(0)->widget());
                btn->setProperty("type","databaseBtn");
                style()->polish(btn);
            }
        }

    }
}



void TransferStorage::on_submit_btn_clicked()
{
    if(ui->type_combo->currentIndex()==-1)
    {
        warning(this,"未选择调拨类型");
        return;
    }
    if(ui->start_date->currentText()==nullptr)
    {
        warning(this,"未选择调拨申请日期");
        return;
    }
    if(ui->end_date->currentText()==nullptr)
    {
        warning(this,"未选择期望到货日期");
        return;
    }
    if(ui->select_member_btn->text()=="选择成员")
    {
        warning(this,"未选择调拨申请人");
        return;
    }
    if(ui->out_storage_combo->currentIndex()==-1)
    {
        warning(this,"未选择调出仓库");
        return;
    }
    if(ui->into_storage_combo->currentIndex()==-1)
    {
        warning(this,"未选择调入仓库");
        return;
    }
    if(ui->tableWidget->rowCount()==0)
    {
        warning(this,"未录入调拨产品明细");
        return;
    }
    else if(CheckTable() == false)
    {
        warning(this,"产品明细录入不完整");
        return;
    }
    else
    {
        for(int i=0;i<ui->tableWidget->rowCount();i++)
        {
            QString str = tableCellText(i,IntoLocation).left(5);
            if(tableCellText(i,TransferNum).toInt() > tableCellText(i,OutStorageNum).toInt()
                    || tableCellText(i,TransferNum).toInt() + tableCellText(i, IntoStorageNum).toInt() > getLocationMAXMUM(Into_type,i,str))
            {
                warning(this,QString("第%1行：产品调拨数量错误").arg(i+1));
                return;
            }
        }
    }

    int ret = QMessageBox::question(this, "上传调库单","确认上传？", QMessageBox::Yes, QMessageBox::No);
    if(ret == QMessageBox::Yes)
    {
        QSqlQuery query;

        //插入 移库单表
        QString sql = QString("INSERT INTO transfer_storage_record_table(TransferStorageRecordID,TransferStorageType,"
                              " OutStorage, IntoStorage, ResponsiblePerson, ApplyDt, DeadlineDt)"
                              " VALUES ('%1','%2','%3','%4','%5','%6','%7');")
                .arg(ui->ID->text())
                .arg(ui->type_combo->currentText())
                .arg(ui->out_storage_combo->currentText())
                .arg(ui->into_storage_combo->currentText())
                .arg(ui->select_member_btn->text().left(ui->select_member_btn->text().indexOf("(")))
                .arg(ui->start_date->currentText())
                .arg(ui->end_date->currentText());
        if(!query.exec(sql))
        {
            warning(this,"上传失败");
            qDebug()<<"移库单表"<<query.lastError();
            return;
        }
        query.clear();  //清空sql语句

        //插入 盘点明细信息表
        query.prepare(QString("INSERT INTO transfer_storage_detail_table(TransferStorageDetailID,ProductCode,ProductType,ProductBatch,OutLocation,"
                              " OutLocationNum, IntoLocation, IntoLocationNum, TransferNum)"
                              " VALUES (:TransferStorageDetailID,:ProductCode,:ProductType,:ProductBatch,:OutLocation,"
                              " :OutLocationNum, :IntoLocation, :IntoLocationNum, :TransferNum);"));
        for(int i=0;i<ui->tableWidget->rowCount();i++)
        {
            query.bindValue(":TransferStorageDetailID",tableCellText(i,DetailID));
            query.bindValue(":ProductCode", tableCellText(i,ProductCode));
            query.bindValue(":ProductType", tableCellText(i,ProductType));
            query.bindValue(":ProductBatch", tableCellText(i,ProductBatch));
            query.bindValue(":OutLocation",tableCellText(i,OutLocation));
            query.bindValue(":OutLocationNum", tableCellText(i,OutStorageNum));
            query.bindValue(":IntoLocation",tableCellText(i,IntoLocation).left(5));  //截取前两位，Y1001 （余58） 取前5位
            query.bindValue(":IntoLocationNum",tableCellText(i,IntoStorageNum));
            query.bindValue(":TransferNum", tableCellText(i,TransferNum));
            if(!query.exec())
            {
                warning(this,"上传失败");
                qDebug()<<"明细信息表"<<query.lastError();
                return;
            }
        }
        query.clear();  //清空sql语句

        //生成调拨出库单
        if(!OutStorage())
        {
            warning(this,"上传失败");
            return;
        }
        //生成调拨入库单
        if(!InStorage())
        {
            warning(this,"上传失败");
            return;
        }

        //插入 移库关系表
        query.prepare(QString("INSERT INTO transfer_storage_relation_table(TransferStorageRecordID,TransferStorageDetailID)"
                              " VALUES (:TransferStorageRecordID,:TransferStorageDetailID);"));

        query.bindValue(":TransferStorageRecordID",ui->ID->text());
        for(int i=0;i<ui->tableWidget->rowCount();i++)
        {
            query.bindValue(":TransferStorageDetailID", tableCellText(i,DetailID));
            if(!query.exec())
            {
                qDebug()<<"移库关系"<<query.lastError();
                warning(this,"上传失败");
                return;
            }
        }
        query.clear();  //清空sql语句

        QMessageBox::information(this, "上传移库单","上传成功");
        clear();
    }
}

void TransferStorage::on_select_member_btn_clicked()
{
    //创建数据选择子界面
    dc=new DataChoose();
    dc->setTitle("选择移库申请员");
    dc->myModel->setQuery("SELECT id, username, position FROM dm_user WHERE delete_flag=0");
    dc->myModel->setHeaderData(0,Qt::Horizontal,"编号");
    dc->myModel->setHeaderData(1,Qt::Horizontal,"姓名");
    dc->myModel->setHeaderData(2,Qt::Horizontal,"职位");
    dc->show();
    //子界面向主界面传送选择的数据
    connect(dc,static_cast<void(DataChoose::*)(const QModelIndexList&)>(&DataChoose::singal_selectedItems),
            this, [this](const QModelIndexList& list)
    {
        ui->select_member_btn->setText(list[0].data().toString() + "(" + list[1].data().toString() + ")");
        ui->select_member_btn->setProperty("type","SelectMember_ed");
        style()->polish(ui->select_member_btn);

    });
}

void TransferStorage::on_type_combo_currentIndexChanged(const QString &arg1)
{
    IDGenerate();           //生成库单号ID
    DetailIDGenerate(0);  //刷新库详细信息
}

void TransferStorage::on_out_storage_combo_currentIndexChanged(const QString &arg1)
{
    Out_type = arg1.right(2);

    IDGenerate();           //生成库单号ID
    DetailIDGenerate(0);  //刷新库详细信息
}

void TransferStorage::on_into_storage_combo_currentIndexChanged(const QString &arg1)
{
    Into_type = arg1.right(2);

    IDGenerate();           //生成库单号ID
    DetailIDGenerate(0);  //刷新库详细信息
}

void TransferStorage::on_start_date_editTextChanged(const QString &arg1)
{
    IDGenerate();           //生成库单号ID
    DetailIDGenerate(0);  //刷新库详细信息
}

void TransferStorage::on_tableWidget_cellChanged(int row, int column) //这里是否要刷新？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？
{
    if(column == DetailID || column == ProductBatch || column == ProductCode)
    {
        DatabaseComboBox *cbbox = (DatabaseComboBox*)( ui->tableWidget->cellWidget(row, OutLocation));
        if(cbbox)
        {
            cbbox->list = getLocationlist(row, true);
            cbbox->setCurrentIndex(-1);
        }
        cbbox = (DatabaseComboBox*)( ui->tableWidget->cellWidget(row, IntoLocation));
        if(cbbox)
        {
            cbbox->list = getLocationlist(row, false);
            cbbox->setCurrentIndex(-1);
        }
    }
}

void TransferStorage::clear()
{
    ui->type_combo->setCurrentIndex(-1);
    ui->start_date->setEditText("");
    ui->end_date->setEditText("");
    ui->select_member_btn->setText("选择成员");
    ui->select_member_btn->setProperty("type","SelectMember");
    style()->polish(ui->select_member_btn);

    ui->ID->setText("");
    ui->out_storage_combo->setCurrentIndex(-1);
    ui->into_storage_combo->setCurrentIndex(-1);
    Out_type = "";
    for(int i = ui->tableWidget->rowCount()-1; i>=0 ; i--)
    {
        RowDelete(i);
    }
}
